package com.originskyseed.platform.course.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.course.mapper.PaperRelateAnswerMapper;
import com.originskyseed.platform.course.mapper.PaperRelateUserMapper;
import com.originskyseed.platform.course.model.Paper;
import com.originskyseed.platform.course.model.PaperRelateAnswer;
import com.originskyseed.platform.course.model.PaperRelateSubject;
import com.originskyseed.platform.course.model.PaperRelateSubjectOption;
import com.originskyseed.platform.course.model.PaperRelateUser;
import com.originskyseed.platform.course.service.IPaperRelateSubjectOptionService;
import com.originskyseed.platform.course.service.IPaperRelateUserService;
import com.originskyseed.platform.task.mapper.TaskRelateAssignPersonMapper;
import com.originskyseed.platform.task.model.TaskRelateAssignPerson;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 试卷关联作答用户信息Service接口实现类（OSI_PAPER_RELATE_USER）
 *
 * @author Tangwanghui
 */
@DubboService
@Component("paperRelateUserService")
public class PaperRelateUserServiceImpl implements IPaperRelateUserService {

	@Resource
	private PaperRelateUserMapper paperRelateUserMapper;

	@Resource
	private PaperRelateAnswerMapper paperRelateAnswerMapper;

	@Resource
	private TaskRelateAssignPersonMapper taskRelateAssignPersonMapper;

	@Resource
	private IPaperRelateSubjectOptionService paperRelateSubjectOptionService;

	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.paperRelateUserMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.paperRelateUserMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(PaperRelateUser record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.paperRelateUserMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(PaperRelateUser record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.paperRelateUserMapper.insertSelective(record);
	}

	/**
	 * 作答记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertPaperAnswer(PaperRelateUser record, List<PaperRelateAnswer> list11, UserInfo userInfo, Paper paper, List<PaperRelateSubject> paperRelateSubjectList) throws Exception {
		BigDecimal score = BigDecimal.ZERO;
		Integer isGrade = 1;
		String answerNum = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
		if (paperRelateSubjectList != null && paperRelateSubjectList.size() > 0) {
			for (PaperRelateSubject paperRelateSubject : paperRelateSubjectList) {
				PaperRelateAnswer paperRelateAnswer = new PaperRelateAnswer();
				// 判断类型
				if (paperRelateSubject.getType() == 1 || paperRelateSubject.getType() == 2 || paperRelateSubject.getType() == 5) { // 单/多/判断题
					if (paperRelateSubject.getPaperRelateSubjectOptionList() != null && paperRelateSubject.getPaperRelateSubjectOptionList().size() > 0) {
						List<PaperRelateSubjectOption> paperRelateSubjectList1 = paperRelateSubject.getPaperRelateSubjectOptionList();
						StringBuffer optionId = new StringBuffer();// 答案
						for (PaperRelateSubjectOption paperRelateSubjectOption : paperRelateSubjectList1) {
							if (paperRelateSubjectOption.getIsAnswer() != null && paperRelateSubjectOption.getIsAnswer() == 1) {
								optionId.append(paperRelateSubjectOption.getId() + ",");// 答案选项
							}
						}
						String optionIdStr = optionId.toString();
						if (optionIdStr != null && StringUtils.isNotBlank(optionIdStr)) {
							paperRelateAnswer.setOptionId(optionId.substring(0, optionId.length() - 1));
						}
					}

					// 单选、多选需要计算分数
					if ((paperRelateSubject.getType() == 1 || paperRelateSubject.getType() == 2 ) && StringUtils.isNotBlank(paperRelateAnswer.getOptionId())) {
						PaperRelateSubjectOption query = new PaperRelateSubjectOption();
						query.setStemId(paperRelateSubject.getId());
						List<PaperRelateSubjectOption> paperRelateSubjectOptionList = this.paperRelateSubjectOptionService.selectList(query);
						StringBuffer optionId = new StringBuffer();// 答案
						for (PaperRelateSubjectOption paperRelateSubjectOption : paperRelateSubjectOptionList) {
							if (paperRelateSubjectOption.getIsAnswer() != null && paperRelateSubjectOption.getIsAnswer() == 1) {
								optionId.append(paperRelateSubjectOption.getId() + ",");// 答案选项
							}
						}
						String optionIdStr = optionId.toString();
						if (optionIdStr != null && StringUtils.isNotBlank(optionIdStr)) {
							optionIdStr = optionIdStr.substring(0, optionIdStr.length() - 1);
							if (optionIdStr.equals(paperRelateAnswer.getOptionId())) {
								paperRelateAnswer.setScore(paperRelateSubject.getScore());
								score = score.add(paperRelateSubject.getScore());
							}
						}
					}
					//判断需要计算分数
					if(paperRelateSubject.getType()==5){
						PaperRelateSubjectOption query = new PaperRelateSubjectOption();
						query.setStemId(paperRelateSubject.getId());
						List<PaperRelateSubjectOption> paperRelateSubjectOptionList = this.paperRelateSubjectOptionService.selectList(query);
						for (PaperRelateSubjectOption paperRelateSubjectOption : paperRelateSubjectOptionList) {
							for (PaperRelateSubjectOption answerPaperSubjectOption:paperRelateSubject.getPaperRelateSubjectOptionList()) {
								if(paperRelateSubjectOption.getIsAnswer()==answerPaperSubjectOption.getIsAnswer()){
									paperRelateAnswer.setScore(paperRelateSubject.getScore());
									score = score.add(paperRelateSubject.getScore());
								}
							}
						}
					}
				} else if (paperRelateSubject.getType() == 3 || paperRelateSubject.getType() == 4) { // 填空题/简答题
					isGrade = 0;
					if (paperRelateSubject.getAnswer() != null || StringUtils.isNotEmpty(paperRelateSubject.getAnswer())) {
						paperRelateAnswer.setContent(paperRelateSubject.getAnswer());
					}
				} else {
					isGrade = 0;
					if (paperRelateSubject.getFilePath() != null || StringUtils.isNotEmpty(paperRelateSubject.getFilePath())) {
						paperRelateAnswer.setFilePath(paperRelateSubject.getFilePath());
						paperRelateAnswer.setFileName(paperRelateSubject.getFileName());
					}
				}
				paperRelateAnswer.setStemId(paperRelateSubject.getId());
				paperRelateAnswer.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
				paperRelateAnswer.setCreateTime(new Date());
				paperRelateAnswer.setCreator(userInfo.getName());
				paperRelateAnswer.setCreatorId(userInfo.getId());
				paperRelateAnswer.setPaperId(paperRelateSubject.getPaperId());
				paperRelateAnswer.setTaskId(record == null ? "" : record.getTaskId());
				paperRelateAnswer.setAnswerNumber(answerNum);
				this.paperRelateAnswerMapper.insertSelective(paperRelateAnswer);
			}
			getPaperRelateUser(record, paper);
			// 关联作答人
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
			record.setScore(score);
			record.setIsGrade(isGrade);
			record.setCreateTime(new Date());
			record.setFinishTime(new Date());
			record.setState(2);// 已提交
			record.setAnswerNumber(answerNum);
			record.setCreator(userInfo.getName());
			record.setCreatorId(userInfo.getId());
			record.setGradeName("自动评卷");
			record.setGradeId(null);
			this.insertSelective(record);
		} else {
			throw new Exception("作答记录为空！");
		}
		return 1;
	}

	private void getPaperRelateUser(PaperRelateUser paperRelateUser, Paper paper) throws Exception {
		TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonMapper.selectPaperIsMyTask(paperRelateUser.getTaskId(), paperRelateUser.getCreatorId());
		if (taskRelateAssignPerson != null) {
			// 大小比较
			int flag = paperRelateUser.getScore().compareTo(paper.getPassingScore());
			if (flag > 0 || flag == 0) { // 及格
				paperRelateUser.setState(2);// 通过
				taskRelateAssignPerson.setState(2);// 完成
				taskRelateAssignPerson.setFinishTime(new Date());
			} else {
				paperRelateUser.setState(3);// 未通过
				taskRelateAssignPerson.setState(1);// 未完成
			}
			this.taskRelateAssignPersonMapper.updateByPrimaryKeySelective(taskRelateAssignPerson);
		}
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(PaperRelateUser record) throws Exception {
		record.setUpdateTime(new Date());
		return this.paperRelateUserMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(PaperRelateUser record) throws Exception {
		record.setUpdateTime(new Date());
		return this.paperRelateUserMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public PaperRelateUser selectByPrimaryKey(String id) throws Exception {
		return this.paperRelateUserMapper.selectByPrimaryKey(id);
	}

	/**
	 * 通过作答人ID查询
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public PaperRelateUser selectByUserId(String id) throws Exception {
		return this.paperRelateUserMapper.selectByUserId(id);
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<PaperRelateUser> selectList(PaperRelateUser record) throws Exception {
		return this.paperRelateUserMapper.selectList(record);
	}

	/**
	 * 查询信息
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public PaperRelateUser selectByPaperRelateUser(PaperRelateUser record) throws Exception {
		return this.paperRelateUserMapper.selectByPaperRelateUser(record);
	}

	@Override
	public PaperRelateUser selectRelateUserIsExam(PaperRelateUser record) throws Exception {
		return this.paperRelateUserMapper.selectRelateUserIsExam(record);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<PaperRelateUser> selectListByPage(Map<String, Object> params, BasePage<PaperRelateUser> page) throws Exception {
		params.put("page", page);
		List<PaperRelateUser> list = this.paperRelateUserMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 分页查询评分列表
	 * 
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<PaperRelateUser> gradeSelectPaperListByPage(Map<String, Object> params, BasePage<PaperRelateUser> page, String taskId) throws Exception {
		params.put("page", page);
		params.put("state", 2);// 查看提交的试卷信息
		List<PaperRelateUser> list = this.paperRelateUserMapper.gradeSelectPaperListByPage(params);
		page.setResults(list);
		return page;
	}

}
